package com.wejoy.video.middle.station.admin.controller.screen;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wejoy.video.middle.station.admin.controller.BaseController;
import com.wejoy.video.middle.station.data.domain.alarm.AlarmDetails;
import com.wejoy.video.middle.station.data.domain.system.SysCarmera;
import com.wejoy.video.middle.station.data.enums.dict.EnumCameraType;
import com.wejoy.video.middle.station.data.enums.dict.EnumYesNo;
import com.wejoy.video.middle.station.data.service.alarm.IAlarmDetailsService;
import com.wejoy.video.middle.station.data.service.evs.IEvsHttpService;
import com.wejoy.video.middle.station.data.service.system.ISysCarmeraService;
import com.wejoy.video.middle.station.data.vo.RespJSON;
import com.wejoy.video.middle.station.data.vo.ScreenAlarmVO;
import com.wejoy.video.middle.station.data.vo.ScreenOverviewVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author miracle_j
 * Create by 2024/12/11 11:24
 */
@RestController
@RequestMapping("/screen/screenUserCarmeraConfig")
public class ScreenController  extends BaseController {

    @Autowired
    private ISysCarmeraService sysCarmeraService;
    @Autowired
    private IAlarmDetailsService alarmDetailsService;

    @Autowired
    private IEvsHttpService evsHttpService;


    @GetMapping("/getPointByTag/{tagId}")
    public RespJSON getPointByTag(@PathVariable Long tagId) {
        List<JSONObject> allData = new ArrayList<>();
        Set<String> uniqueTagNames = new HashSet<>(); // 存储去重的站点名称
        int pageNo = 1;
        int pageSize = 90;
        int totalCount = 0;

        do {
            JSONObject response = evsHttpService.getPointTagInfo(evsHttpService.getToken(), tagId, pageNo, pageSize);
//            JSONObject response = JSONObject.parseObject("{\"data\":[{\"pointId\":200000099,\"areaId\":1000025,\"paasChannelId\":1000014,\"pointName\":\"MVA49-配电间\",\"alias\":\"\",\"shareGbId\":\"\",\"parentDeviceId\":100000023,\"gbId\":\"31023000001320000103\",\"platformType\":\"GB28181_2016\",\"deviceType\":\"NVR\",\"parentDeviceName\":\"阀室MVA49-NVR1\",\"areaPath\":\"上燃项目/阀室\",\"followed\":false,\"basePath\":\"上燃项目/阀室\",\"pointStatus\":\"ONLINE\",\"geo\":{\"location\":\"192.168.254.6\"},\"catalogueId\":1000007,\"coverUrl\":\"https://evs.sgpnc.com:8999/evs-app-platform/cover/200000099?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20250326T131422Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=gatewayak%2F20250326%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Signature=4d197d8498dc0b21965569b4f090c254e02e2ca0989ee7eddce3be7c82ee70d3\",\"favoriteStatus\":false,\"markStatus\":true,\"governanceStatus\":\"NO_GOVERNANCE\",\"tags\":[{\"type\":\"设备类型\",\"tagNames\":[\"枪机\"]},{\"type\":\"场站类型\",\"tagNames\":[\"阀室\"]},{\"type\":\"设备厂站\",\"tagNames\":[\"MVA49\",\"MVA49/121.482229998233,31.0558827812476\"]}]},{\"pointId\":200000100,\"areaId\":1000025,\"paasChannelId\":1000013,\"pointName\":\"MVA49-主阀室\",\"alias\":\"\",\"shareGbId\":\"\",\"parentDeviceId\":100000023,\"gbId\":\"31023000001320000102\",\"platformType\":\"GB28181_2016\",\"deviceType\":\"NVR\",\"parentDeviceName\":\"阀室MVA49-NVR1\",\"areaPath\":\"上燃项目/阀室\",\"followed\":false,\"basePath\":\"上燃项目/阀室\",\"pointStatus\":\"ONLINE\",\"geo\":{\"location\":\"192.168.254.7\"},\"catalogueId\":1000007,\"coverUrl\":\"https://evs.sgpnc.com:8999/evs-app-platform/cover/200000100?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Date=20250326T131422Z&X-Amz-SignedHeaders=host&X-Amz-Expires=86400&X-Amz-Credential=gatewayak%2F20250326%2Fus-west-2%2Fs3%2Faws4_request&X-Amz-Signature=b1def16b64504c6dc98da712a127e69322e7de05251c0a5402d8f7a4fe916ad0\",\"favoriteStatus\":false,\"markStatus\":true,\"governanceStatus\":\"NO_GOVERNANCE\",\"tags\":[{\"type\":\"设备类型\",\"tagNames\":[\"枪机\"]},{\"type\":\"场站类型\",\"tagNames\":[\"阀室\"]},{\"type\":\"设备厂站\",\"tagNames\":[\"MVA49\",\"MVA49/121.482229998233,31.0558827812476\"]}]}],\"pageNo\":1,\"pageSize\":90,\"totalCount\":2}");
            JSONArray data = response.getJSONArray("data");
            // 如果 data 为空或者 totalCount 小于等于当前数据量，停止循环
            totalCount = response.getIntValue("totalCount");
            if (data == null || data.isEmpty() || allData.size() >= totalCount) {
                break;
            }

            if (data != null) {
                for (int i = 0; i < data.size(); i++) {
                    JSONObject point = data.getJSONObject(i);
                    JSONArray tags = point.getJSONArray("tags");

                    if (tags == null) {
                        allData.add(point);
                        continue;
                    }

                    String stationName = null; // 站点名称
                    Double longitude = null, latitude = null; // 经纬度

                    for (int j = 0; j < tags.size(); j++) {
                        JSONObject tag = tags.getJSONObject(j);

                        if ("设备厂站".equals(tag.getString("type"))) {
                            JSONArray tagNames = tag.getJSONArray("tagNames");

                            if (!CollectionUtils.isEmpty(tagNames)) {
                                stationName = tagNames.getString(0); // 获取站点名称

                                // 查找包含经纬度的数据
                                for (String tagName : tagNames.toJavaList(String.class)) {
                                    if (tagName.contains("/") && tagName.split("/")[1].contains(",")) {
                                        String[] coords = tagName.split("/")[1].split(",");
                                        if (coords.length == 2) {
                                            try {
                                                longitude = Double.parseDouble(coords[0]);
                                                latitude = Double.parseDouble(coords[1]);
                                            } catch (NumberFormatException ignored) {
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // 如果站点名称已存在，跳过该 point
                    if (stationName != null && !uniqueTagNames.add(stationName)) {
                        continue;
                    }

                    // 添加经纬度信息
                    if (longitude != null && latitude != null) {
                        point.put("deviceLongitude", longitude);
                        point.put("deviceLatitude", latitude);
                    }else {
                        // 没有经纬度 跳过该 point
                        continue;
                    }

                    allData.add(point);
                }
            }

            pageNo++;
        } while (allData.size() < totalCount);

        return RespJSON.success(allData);
    }



    @GetMapping("/getPointListByTag/{tagName}")
    public RespJSON getPointListByTag(@PathVariable String tagName,Integer pageNo,Integer pageSize) {
        JSONObject tags = evsHttpService.getTags(evsHttpService.getToken(), -1L, "1000019");
        JSONArray data = tags.getJSONArray("data");
        if (data != null) {
            for (int i = 0; i < data.size(); i++) {
                JSONObject tag = data.getJSONObject(i);
                if (tagName.equals(tag.getString("name"))) {
                    Long pointId = tag.getLong("id");
                    JSONObject response = evsHttpService.getPointTagInfo(evsHttpService.getToken(), pointId, pageNo, pageSize);
                    return RespJSON.success(response);
                }
            }
        }
        return RespJSON.success();
    }


    /**
     * 监控概况-驾驶舱首页
     * @return
     */
    @RequestMapping("/getOverview")
    public RespJSON getOverview(){
        ScreenOverviewVO screenOverviewVO = new ScreenOverviewVO();
        SysCarmera sysCarmera = new SysCarmera();
        int count = sysCarmeraService.getCount(sysCarmera);
        sysCarmera.setIsAi(Boolean.FALSE);
        screenOverviewVO.setMonitorCount(count);
        screenOverviewVO.setNoAiMonitorCount(sysCarmeraService.getCount(sysCarmera));
        screenOverviewVO.setAiMonitorCount(screenOverviewVO.getMonitorCount()-screenOverviewVO.getNoAiMonitorCount());
        sysCarmera.setIsAi(null);
        //各个类型设备总数
        sysCarmera.setCameraType(EnumCameraType.VIDEO_MONITOR.getCode());
        screenOverviewVO.setVideoMonitorCount(sysCarmeraService.getCount(sysCarmera));
        sysCarmera.setCameraType(EnumCameraType.DRONE.getCode());
        screenOverviewVO.setDroneMonitorCount(sysCarmeraService.getCount(sysCarmera));
        sysCarmera.setCameraType(EnumCameraType.LAW_MONITOR.getCode());
        screenOverviewVO.setLawMonitorCount(sysCarmeraService.getCount(sysCarmera));
        //各个类型设备在离线数量
        sysCarmera.setOnline(Boolean.TRUE);
        screenOverviewVO.setLawMonitorOnlineCount(sysCarmeraService.getCount(sysCarmera));
        screenOverviewVO.setLawMonitorOfflineCount(screenOverviewVO.getLawMonitorCount()-screenOverviewVO.getLawMonitorOnlineCount());
        sysCarmera.setCameraType(EnumCameraType.VIDEO_MONITOR.getCode());
        screenOverviewVO.setVideoMonitorOnlineCount(sysCarmeraService.getCount(sysCarmera));
        screenOverviewVO.setVideoMonitorOfflineCount(screenOverviewVO.getVideoMonitorCount()-screenOverviewVO.getVideoMonitorOnlineCount());
        sysCarmera.setCameraType(EnumCameraType.DRONE.getCode());
        screenOverviewVO.setDroneMonitorOnlineCount(sysCarmeraService.getCount(sysCarmera));
        screenOverviewVO.setDroneMonitorOfflineCount(screenOverviewVO.getDroneMonitorCount()-screenOverviewVO.getDroneMonitorOnlineCount());
        return RespJSON.success(screenOverviewVO);
    }

    /**
     * 监控概况-驾驶舱首页
     * @return
     */
    @PostMapping("/getAlarms")
    public RespJSON getAlarms(@RequestBody AlarmDetails alarmDetails){
        ScreenAlarmVO screenAlarmVO = new ScreenAlarmVO();
        SysCarmera sysCarmera = new SysCarmera();
        //各种设备告警数量
        sysCarmera.setOnline(null);
        alarmDetails.setDeviceType(EnumCameraType.DRONE.getCode().longValue());
        screenAlarmVO.setDroneMonitorAlarmCount(alarmDetailsService.getCount(alarmDetails));
        alarmDetails.setDeviceType(EnumCameraType.LAW_MONITOR.getCode().longValue());
        screenAlarmVO.setLawMonitorAlarmCount(alarmDetailsService.getCount(alarmDetails));
        alarmDetails.setDeviceType(EnumCameraType.VIDEO_MONITOR.getCode().longValue());
        screenAlarmVO.setVideoMonitorAlarmCount(alarmDetailsService.getCount(alarmDetails));
        //各种设备当前告警数量
        alarmDetails.setOrderStatus(EnumYesNo.YES.getCode());
        alarmDetails.setDeviceType(EnumCameraType.DRONE.getCode().longValue());
        screenAlarmVO.setDroneMonitorCurrentAlarmCount(alarmDetailsService.getCount(alarmDetails));
        alarmDetails.setDeviceType(EnumCameraType.LAW_MONITOR.getCode().longValue());
        screenAlarmVO.setLawMonitorCurrentAlarmCount(alarmDetailsService.getCount(alarmDetails));
        alarmDetails.setDeviceType(EnumCameraType.VIDEO_MONITOR.getCode().longValue());
        screenAlarmVO.setVideoMonitorCurrentAlarmCount(alarmDetailsService.getCount(alarmDetails));
        return RespJSON.success(screenAlarmVO);
    }


}
